<?php
/**
 * 工具箱
 */
namespace services;
use fast\Http;
class MeishikaiService
{

    private $url;

    private function init()
    {
    }

    public function __construct()
    {
        $this->init();
        $this->__loader();
        $this->url = '';
    }

    private function __loader()
    {
    }


    
    /**
     * 登录工具箱
     * @DateTime 2023-04-18T14:24:51+0800
     * {"Content":{"ApiToken":"-","AuthTypes":"1","BindingCode":"738325","CustomerType":"员工","DatCreate":"2024-12-05T16:49:01","DatUpdate":"2024-12-17T09:20:50","Duties":"审核员","HeadPicUrl":"","ID":492,"IsEnabled":true,"IsMaster":true,"MembershipLevel":"定制会员","NickName":"夏春红","OrganizeIds":"515","Password":"7fba949d8fde019ae87bd8f3b9014873","Phone":"18072725357","RightsIdList":"69,18,38,39,40,15,63,10,11,13,93","RoleId":322,"SettlementMethod":"租用","SystemKeys":"GJX","TenantID":308,"UserName":"18072725357","UserToolType":1,"WxGroupName":"","BrandName":"杭州俱美科技有限公司","OrganizeNames":null,"DeviceUuid":"7fba949d8fde019a","Token":"492,eae2787b78a49aaed53c8a1208ae40f36cf551dfb51cbe69fede972fc2d50610","DatExpired":"2025-01-05T14:28:34","OnlineID":11729,"ContractTypeFZXT":"暂无合约","ContractTerminationDateFZXT":"1900-01-01T00:00:00","ContractTypeGJX":"试用客户","ContractTerminationDateGJX":"9999-12-15T00:00:00","ContractTypeDHXT":"暂无合约","ContractTerminationDateDHXT":"1900-01-01T00:00:00","Status":1,"ErpRole":null,"ErpOrganizeList":null},"IsSuccess":true,"StatusCode":200,"Message":""}
     */
    public function userLogin()
    {
        $this->url = 'https://merchantapi.meishikai.cn/api/User/UserLogin';
        $param = [
          'LoginType' => 0,
          'UserName' => "18072725357",
          'Password' => "123456",
          'DeviceUuid' => "7fba949d8fde019a",
          'Captcha' => "",
        ];
        $params = json_encode($param);
        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
        return Http::post($this->url,$params,[],$header);
    }


    
    /**
     * 添加平台账号（用插件方式）
     * @DateTime 2023-04-18T14:24:51+0800
     * {"Content":{"ShopTotal":0,"DeleteTotal":0,"MeituanApiInvalidTotal":0,"UserreferList":null,"AccessToken":"","Expire":0,"IsApiInvalid":false,"RefreshToken":"","UpdateFlag":"","ID":93777,"TenantID":308,"PChannel":"美团","PUserId":"wmjlxj6517645","ShopName":"疆来·新疆炒米粉（滨河店）","Password":"SofnK31659","UserName":"wmjlxj6517645","Phone":"","LoginType":1,"ShopType":0,"DatCreate":"2024-12-30T09:03:20","DatUpdate":"2024-12-30T09:03:20","IsTokenInvalid":true,"JsonExpand":"{}"},"IsSuccess":true,"StatusCode":200,"Message":"新增平台账号成功"}
     */
    public function setModel($token,$username,$shoptype,$password='',$shopname='')
    {
        $this->url = 'https://merchantapi.meishikai.cn/api/Platformaccount/SetModel?token='.$token;
        $param = [
          'Status' => 1,
          'PChannel' => $shoptype,
          'LoginType' => 1,
          'Phone' => "",
          'UserName' => $username,
          'Password' => "",
          'ShopName' => "",
          'PUserId' => $username,
          'IsUpdateUserRefer' => true,
          'IsTokenInvalid' => true,
          'IsApiInvalid' => true,
          // 'UserreferList' => [],
        ];
        $params = json_encode($param);
        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
        return Http::post($this->url,$params,[],$header);
    }


    
    /**
     * 添加平台账号（非插件方式）美团
     * @DateTime 2023-04-18T14:24:51+0800
     * {"Content":"https://open-erp.meituan.com/login?ePoiId=1873536977941434368×tamp=1735520998&businessId=16&charset=utf-8&developerId=107758&sign=f069012dfd1ccc3045c6d4267102519129a9440f","IsSuccess":true,"StatusCode":200,"Message":""}
     */
    public function mtAuthorize($token,$accountid,$username)
    {
        $this->url = 'https://sysapi.meishikai.cn/api/Mt/Authorize?accountId='.$accountid.'&userName='.$username;
        return file_get_contents($this->url);
    }


    
    /**
     * 添加平台账号（非插件方式）饿了么
     * @DateTime 2023-04-18T14:24:51+0800
     * {"Content":"https://open-erp.meituan.com/login?ePoiId=1873536977941434368×tamp=1735520998&businessId=16&charset=utf-8&developerId=107758&sign=f069012dfd1ccc3045c6d4267102519129a9440f","IsSuccess":true,"StatusCode":200,"Message":""}
     */
    public function elmAuthorize($token,$tenantid,$username)
    {
        $this->url = 'https://sysapi.meishikai.cn/api/Elm/GeAuthUrl?callbackUrl='.$tenantid.'|^'.$username;
        return file_get_contents($this->url);
    }


    
    /**
     * 刷新授权
     * @DateTime 2023-04-18T14:24:51+0800
     */
    public function synchronizeRefresh($token,$authtypes,$tenantid,$username)
    {
        $this->url = 'https://extraapi.meishikai.cn/synchronize_refresh/account/store';
        $param = [
          'auth_types' => $authtypes,
          'api_token' => $token,
          'tenants_id' => $tenantid,
          'p_userid' => $username,
          'channel' => "美团",
        ];
        $params = json_encode($param);
        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
        return Http::post($this->url,$params,[],$header);
    }


    
    /**
     * 店铺列表
     * @DateTime 2023-04-18T14:24:51+0800
     * {"Content":{"RecordCount":1,"RecordList":[{"OrgId":515,"OrgIdPath":"515","OrgName":"杭州俱美科技有限公司","ShopId":0,"RefShopId":151087,"BusinessHours":"","IsEffective":true,"PUserId":"wmjlxj6517645","IsDeleted":false,"IsDeactivate":true,"BusinessStatus":false,"DatExpire":"2024-12-31T00:00:00","ID":0,"PChannel":"美团","PShopId":"24857368","ShopName":"疆味·新疆炒米粉（滨河店）","Uid":"","JsonData":"","Address":"","ProvinceName":"","CityName":"","Phone":"","DatCreate":"2024-12-31T11:15:37","DatUpdate":"1900-01-01T00:00:00","Latitude":0.0,"Longitude":0.0,"UpdateOper":"","MinBudget":10.0,"MinPrice":0.1}]},"IsSuccess":true,"StatusCode":200,"Message":""}
     */
    public function getShopList($token,$page,$channel,$PShopIdList=[])
    {
        $this->url = 'https://merchantapi.meishikai.cn/api/Platformshop/GetList?token='.$token;
        $param = [
          'PageSize' => 100,
          'CurrPage' => $page,
          'OrgIdPath' => "",
          'PChannel' => $channel,
          'PShopIdList' => $PShopIdList,
          'selCity' => [],
          'selTag' => [],
          'ShopType' => 0,
          'IsDeleted' => false,
        ];
        $params = json_encode($param);
        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
        return Http::post($this->url,$params,[],$header);
    }


    
    /**
     * 获取平台订单详情
     * @DateTime 2023-04-18T14:24:51+0800
     * {"Content":{"orderId":2801404720991858855,"poiId":24857368,"epoiId":"1873925209384423424","recipientAddress":"为保护用户隐私具体地址已隐藏","recipientPhone":"手机尾号7926","recipientName":"岳先生","shippingFee":4.2,"total":18.87,"originalPrice":55.2,"caution":"顾客需要餐具","shipperPhone":"骑手手机尾号1391","status":8,"deliveryTime":0,"payType":2,"pickType":0,"daySeq":9,"logisticsCode":"2002","detail":[{"app_food_code":"default","food_name":"焦香黄金豆（加饭里）","sku_id":"default","quantity":1.0,"price":0.1,"box_num":1.0,"box_price":0.0,"unit":"50克","food_property":"50克","spec":"","mt_sku_id":19984256191,"mt_spu_id":6201620626,"mt_tag_id":11532669006,"tag_name":"疆味福利"},{"app_food_code":"default","food_name":"营养煎蛋","sku_id":"default","quantity":1.0,"price":0.99,"box_num":1.0,"box_price":0.0,"unit":"1个","food_property":"1个","spec":"","mt_sku_id":19984256189,"mt_spu_id":6201620624,"mt_tag_id":11532669006,"tag_name":"疆味福利"},{"app_food_code":"default","food_name":"烤热狗肠","sku_id":"default","quantity":1.0,"price":1.98,"box_num":1.0,"box_price":0.0,"unit":"1个","food_property":"1个","spec":"","mt_sku_id":19984256188,"mt_spu_id":6201620627,"mt_tag_id":11532669006,"tag_name":"疆味福利"},{"app_food_code":"default","food_name":"火腿海麦斯（火腿炒粉+馕+年糕+鱼排）","sku_id":"default","quantity":1.0,"price":21.8,"box_num":1.0,"box_price":1.0,"unit":"1人份","food_property":"1人份,微辣","spec":"","mt_sku_id":17439329522,"mt_spu_id":27973170159,"mt_tag_id":11532668993,"tag_name":"店长推荐"}],"activity":[{"act_detail_id":0,"reduce_fee":16.2,"mt_charge":0.0,"poi_charge":16.2,"remark":"购买火腿海麦斯（火腿炒粉+馕+年糕+鱼排）原价38.0元现价21.8元","type":17},{"act_detail_id":0,"reduce_fee":4.9,"mt_charge":0.0,"poi_charge":4.9,"remark":"购买焦香黄金豆（加饭里）原价5.0元现价0.1元","type":17},{"act_detail_id":0,"reduce_fee":2.02,"mt_charge":0.0,"poi_charge":2.02,"remark":"购买烤热狗肠原价4.0元现价1.98元","type":17},{"act_detail_id":0,"reduce_fee":2.01,"mt_charge":0.0,"poi_charge":2.01,"remark":"购买营养煎蛋原价3.0元现价0.99元","type":17},{"act_detail_id":0,"reduce_fee":3.2,"mt_charge":0.5,"poi_charge":2.7,"remark":"减配送费3.2元","type":25},{"act_detail_id":274839715,"reduce_fee":8.0,"mt_charge":3.0,"poi_charge":5.0,"remark":"用户使用了支付红包减8元","type":9}],"latitude":34.6692,"longitude":113.81112,"orderSendTime":1735618078,"orderConfirmTime":1735618520,"orderReceiveTime":0,"orderCancelTime":0,"orderCompletedTime":1735620851,"logisticsSendTime":1735618079,"logisticsConfirmTime":1735618389,"logisticsCancelTime":0,"logisticsFetchTime":1735618520,"logisticsCompletedTime":1735620851,"poi_receive_detail":"{\"wmPoiReceiveCent\":1358,\"actOrderChargeByMt\":[{\"feeTypeId\":10019,\"feeTypeDesc\":\"活动款\",\"moneyCent\":350,\"comment\":\"活动款\"}],\"actOrderChargeByPoi\":[{\"feeTypeId\":10019,\"feeTypeDesc\":\"活动款\",\"moneyCent\":1620,\"comment\":\"购买火腿海麦斯（火腿炒粉+馕+年糕+鱼排）原价38.0元现价21.8元\"},{\"feeTypeId\":10019,\"feeTypeDesc\":\"活动款\",\"moneyCent\":490,\"comment\":\"购买焦香黄金豆（加饭里）原价5.0元现价0.1元\"},{\"feeTypeId\":10019,\"feeTypeDesc\":\"活动款\",\"moneyCent\":202,\"comment\":\"购买烤热狗肠原价4.0元现价1.98元\"},{\"feeTypeId\":10019,\"feeTypeDesc\":\"活动款\",\"moneyCent\":201,\"comment\":\"购买营养煎蛋原价3.0元现价0.99元\"},{\"feeTypeId\":10019,\"feeTypeDesc\":\"活动款\",\"moneyCent\":270,\"comment\":\"减配送费3.2元\"},{\"feeTypeId\":10019,\"feeTypeDesc\":\"活动款\",\"moneyCent\":500,\"comment\":\"用户使用了支付红包减8元\"}],\"foodShareFeeChargeByPoi\":149,\"onlinePayment\":1887,\"logisticsFee\":420,\"reconciliationExtras\":\"{\\\"performanceServiceFee\\\":3.1}\"}","userIdView":11866604214},"IsSuccess":true,"StatusCode":200,"Message":""}
     */
    public function getOrderDetails($token,$channel,$pshopid,$orderid)
    {
        $this->url = 'https://merchantapi.meishikai.cn/api/CustomerBusiness/GetOrderDetails?token='.$token;
        $param = [
          'PChannel' => $channel,
          'PShopId' => $pshopid,
          'OrderId' => $orderid,
        ];
        $params = json_encode($param);
        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
        return Http::post($this->url,$params,[],$header);
        // 美团：
        // status  int 
        // 订单状态 2 新订单，4 已接单，8 订单完成，9 订单取消

        // 饿了么：
        // pending String    
        // 未生效订单
        // unprocessed String    
        // 未处理订单
        // refunding String    
        // 退单处理中
        // valid String    
        // 已处理的有效订单
        // invalid String    
        // 无效订单
        // settled String    
        // 已完成订单
    }


    
    /**
     * 激活门店/停用门店
     * @DateTime 2023-04-18T14:24:51+0800
     */
    // public function updateRefer($token,$channel,$id,$username,$state,$StoreRenewalStatus=0)
    // {
    //     $this->url = 'https://merchantapi.meishikai.cn/api/Platformshop/UpdateRefer?token='.$token;
    //     $param = [
    //       'PChannel' => $channel,//平台名称（可选：美团、饿了么）
    //       'PShopId' => $id,//平台店铺 ID
    //       'PUserId' => $username,//平台账号（停用门店时不要给此属性）
    //       'IsDeactivate' => $state,//停用状态（false：激活，true：停用）
    //       'StoreRenewalStatus' => $StoreRenewalStatus,//门店续费状态，激活时参数有效（1：开启自动续费、0：不开启自动续费）
    //     ];
    //     $params = json_encode($param);
    //     $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
    //     return Http::post($this->url,$params,[],$header);
    // }


    
    /**
     * 订单查询接口
     * @DateTime 2023-04-18T14:24:51+0800
     */
    // public function getList($token,$page,$orderid,$id,$channel)
    // {
    //     $create_start = time()-86400;
    //     $create_end = time();
    //     $complete_start = time()-86400;
    //     $complete_end = time();
    //     $this->url = 'https://merchantapi.meishikai.cn/api/Order/GetList?token='.$token;
    //     $param = [
    //       'PageSize' => 50,
    //       'CurrPage' => $page,
    //       'POrderId' => $orderid,//平台订单号
    //       'PShopId' => $id,//平台店铺 ID
    //       'PChannel' => $channel,//平台名称（可选：美团、饿了么）
    //       'StatusList' => [0],//订单状态（未解析订单:0 ,新订单:2 ,已确认订单:4 ,订单完成:8 ,订单取消:9 ,部分退款:10）
    //       'StatusAudited' => 1,//审核状态(0 未审核，1 已审核)
    //       'DatCreate_Begin' => date('Y-m-d',$create_start).'T'.date('H:i:s',$create_start).'.001Z',//订单创建开始时间
    //       'DatCreate_End' => date('Y-m-d',$create_end).'T'.date('H:i:s',$create_end).'.001Z',//订单创建结束时间
    //       'IsGroupBuying' => false,//是否拼好饭订单
    //       'CompletionDat_Begin' => date('Y-m-d',$complete_start).'T'.date('H:i:s',$complete_start).'.001Z',//订单完成结束时间
    //       'CompletionDat_End' => date('Y-m-d',$complete_end).'T'.date('H:i:s',$complete_end).'.001Z',//订单完成结束时间
    //     ];
    //     $params = json_encode($param);
    //     $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
    //     return Http::post($this->url,$params,[],$header);
    // }


}